import React, { useRef, useState} from 'react';
import {useLocation} from 'umi';
import {delayStat} from '@/services/delay-stat-api'
import {ProCard, ProFormDateTimeRangePicker, QueryFilter} from "@ant-design/pro-components";
import moment from "moment";
import {Line} from "@ant-design/plots";
import {Datum} from "@ant-design/plots/es/interface";



export type DelayStatProps = {
  pipelineId?:number;
}
const DelayStat: React.FC<DelayStatProps> = (props) => {

  const formRef = useRef();
  const [renderTimeData, setRenderTimeData] = useState<any[]>();
  const [renderSizeData, setRenderSizeData] = useState<any[]>();
  const location = useLocation();
  // @ts-ignore
  const pipelineId = props?.pipelineId || location?.state?.pipelineId || null;

  const queryDelayStat = async (values: any) => {

    let data: API.DelayStatInfoDTO = await delayStat({pipelineId: pipelineId, ...values});

    const times = data?.delayStatInfos?  Object.entries(data.delayStatInfos)
      ?.map(([k, v]) => ({x: moment(Number(k)).format('YYYY-MM-DD HH:mm:ss'), value: v?.avgDelayTime, category: '平均延迟（ms）'})) : undefined;

    if (times) {
      setRenderTimeData(times)
    }
    const sizes = data?.delayStatInfos?  Object.entries(data.delayStatInfos)
      ?.map(([k, v]) => ({x: moment(Number(k)).format('YYYY-MM-DD HH:mm:ss'), value: v?.avgDelayNumber, category: '平均延迟数'})) : undefined;
    if (sizes) {
      setRenderSizeData(sizes)
    }
  }
  const DelayStatLine = (data: { data: Datum }) => {
    const config = {
      data: data.data,
      xField: 'x',
      yField: 'value',
      sizeField: 'value',
      shapeField: 'trail',
      legend: {size: false},
      colorField: 'category',
    };
    return <Line {...config} />;
  };

  return (

      <ProCard direction="column" ghost gutter={[0, 16]}>
        <ProCard>
          <QueryFilter formRef={formRef} onFinish={queryDelayStat} span={12} split onInit={queryDelayStat}>
            <ProFormDateTimeRangePicker
              name={["startTime", "endTime"]}
              fieldProps={{format: 'YYYY-MM-DD HH:mm'}}
              transform={values => values ? {
                startTime: moment(values[0]).valueOf(),
                endTime: moment(values[1]).valueOf()
              } : null}
              label="时间区间"
            />
          </QueryFilter>
        </ProCard>
        <ProCard tabs={{type: 'line'}} >
          <ProCard.TabPane key="time" tab="延迟时间（ms）">
            <DelayStatLine data={renderTimeData}/>
          </ProCard.TabPane>
        </ProCard>
      </ProCard>
  );
};

export default DelayStat;
